import pako from 'pako';

function encrypt(str: string) {
  if (str.trim() !== '') {
    let bs = pako.gzip(encodeURIComponent(str), {to: 'string'})
    return window.btoa(bs);
  }
  return '';
}

function decrypt(str: string) {
  let strData = window.atob(str)
  // Convert binary string to character-number array
  let charData = strData.split('').map(function (x) {
    return x.charCodeAt(0)
  });
  // Turn number array into byte-array
  let binData = new Uint8Array(charData)
  // unzip
  let data = pako.inflate(binData)
  // Convert gunzipped byteArray back to ascii string:
  let chunk = 16 * 1024;
  let i;
  let res = '';
  for (i = 0; i < data.length / chunk; i++) {
    res += String.fromCharCode.apply(null, data.slice(i * chunk, (i + 1) * chunk));
  }
  res += String.fromCharCode.apply(null, data.slice(i * chunk));
  // strData = String.fromCharCode.apply(null, new Uint16Array(data))
  return res
}

function decryptNotBase64(str: string) {
  let strData = str;
  let charData = strData.split('').map(function (x) {
    return x.charCodeAt(0)
  });
  let data = pako.inflate(new Uint8Array(charData), {to: 'string'});
  strData = String.fromCharCode.apply(null, new Uint16Array(data) as any);
  return strData
}

export {encrypt, decrypt, decryptNotBase64}
